package com.shopping.controller;


import com.shopping.commons.CurUserInfo;
import com.shopping.commons.Result;
import com.shopping.model.Car;
import com.shopping.service.CarService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/car")

public class CarController {
    @Resource
    private CarService carService;
    //注入session
    @Resource
    private HttpSession session;


    @PostMapping("/addCar")
    public Result addCar(@RequestBody Car car) {
        try {
            CurUserInfo curUserInfo = (CurUserInfo) session.getAttribute("curUserInfo");
            car.setUser_id(curUserInfo.getUser_id());
            carService.addCar(car);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "商品添加失败!!!");
        }
    }

    @GetMapping("/queryCarInfo")
    public List<Car> queryCarInfo() {
        CurUserInfo curUserInfo = (CurUserInfo) session.getAttribute("curUserInfo");
        return carService.queryCarInfo(curUserInfo.getUser_id());
    }

   @PutMapping("/updateCarCount")
    public Result updateCarCount(@RequestBody Car car){
       try {
           CurUserInfo curUserInfo = (CurUserInfo) session.getAttribute("curUserInfo");
           car.setUser_id(curUserInfo.getUser_id());
           carService.updateCarCount(car);
           return Result.success();
       } catch (Exception e) {
           e.printStackTrace();
           return Result.fail(500, "数字不能为0");
       }
   }

   @DeleteMapping("/delCarByBookId")
   public Result delCarByBookId(Integer book_id){
       try {
           CurUserInfo curUserInfo = (CurUserInfo) session.getAttribute("curUserInfo");
           carService.delCarByBookId(curUserInfo.getUser_id(),book_id);
           return Result.success();
       } catch (Exception e) {
           e.printStackTrace();
           return Result.fail(500, "删除失败!!");
       }
   }

   @GetMapping("/getCarCount")
    public Integer getCarCount(){
       CurUserInfo curUserInfo = (CurUserInfo) session.getAttribute("curUserInfo");
       return carService.getCarCount(curUserInfo.getUser_id());
   }

}
